<template>
  <div class="orders-list">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="date-filter">
          <label>日期范围:</label>
          <div class="date-inputs">
            <input 
              type="date" 
              v-model="filters.startDate" 
              class="date-input" 
              :max="filters.endDate"
              @change="handleFilter"
            />
            <span class="date-separator">至</span>
            <input 
              type="date" 
              v-model="filters.endDate" 
              class="date-input" 
              :min="filters.startDate"
              @change="handleFilter"
            />
          </div>
        </div>
        <div class="status-filter">
          <label>订单状态:</label>
          <select v-model="filters.status" class="status-select" @change="handleFilter">
            <option value="">全部状态</option>
            <option value="pending">待处理</option>
            <option value="processing">处理中</option>
            <option value="completed">已完成</option>
            <option value="cancelled">已取消</option>
          </select>
        </div>
        <button class="reset-btn" @click="resetFilters">
          <i class="fas fa-redo-alt"></i> 重置筛选
        </button>
      </div>
    </div>
    
    <!-- 订单表格 -->
    <div class="table-container">
      <table class="orders-table" v-if="!loading && filteredOrders.length > 0">
        <thead>
          <tr>
            <th>订单编号</th>
            <th>下单时间</th>
            <th>产品信息</th>
            <th>订单金额</th>
            <th>佣金金额</th>
            <th>订单状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="order in paginatedOrders" :key="order.id">
            <td>{{ order.id }}</td>
            <td>{{ order.orderTime }}</td>
            <td class="products-cell">
              <div v-for="(product, index) in order.products" :key="index" class="product-item">
                {{ product.name }} x{{ product.quantity }}
                <span class="product-price">¥{{ product.price.toFixed(2) }}</span>
              </div>
              <div class="product-count" v-if="order.products.length > 1">
                共 {{ order.products.length }} 件商品
              </div>
            </td>
            <td class="amount-cell">¥{{ order.totalAmount.toFixed(2) }}</td>
            <td class="commission-cell">¥{{ order.commission.toFixed(2) }}</td>
            <td>
              <span :class="['status-badge', `status-${order.status}`]">
                {{ getStatusText(order.status) }}
              </span>
            </td>
            <td>
              <button class="view-btn" @click="viewOrderDetail(order)">
                <i class="fas fa-eye"></i> 查看详情
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <!-- 加载中状态 -->
      <div class="loading-container" v-if="loading">
        <div class="spinner"></div>
        <p>加载订单数据中...</p>
      </div>
      
      <!-- 空状态 -->
      <div class="empty-container" v-if="!loading && filteredOrders.length === 0">
        <i class="fas fa-file-invoice-dollar"></i>
        <p>暂无订单数据</p>
        <button class="reset-btn" v-if="isFiltered" @click="resetFilters">清除筛选条件</button>
      </div>
    </div>
    
    <!-- 分页控件 -->
    <div class="pagination" v-if="!loading && filteredOrders.length > 0">
      <button 
        class="page-btn" 
        :disabled="currentPage === 1" 
        @click="currentPage--"
      >
        <i class="fas fa-chevron-left"></i>
      </button>
      
      <div class="page-numbers">
        <button 
          v-for="page in displayedPages" 
          :key="page" 
          :class="['page-number', { active: currentPage === page }]"
          @click="currentPage = page"
        >
          {{ page }}
        </button>
      </div>
      
      <button 
        class="page-btn" 
        :disabled="currentPage === totalPages" 
        @click="currentPage++"
      >
        <i class="fas fa-chevron-right"></i>
      </button>
      
      <div class="page-info">
        {{ currentPage }} / {{ totalPages }} 页，共 {{ filteredOrders.length }} 条
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { generateDistributorOrdersData } from '@/utils/agentMock';
import { format, subDays, parseISO } from 'date-fns';

// 定义接口
interface Product {
  name: string;
  quantity: number;
  price: number;
  amount: number;
}

interface Order {
  id: string;
  distributorId: string;
  orderTime: string;
  products: Product[];
  totalAmount: number;
  commission: number;
  status: string;
  customerName: string;
  customerPhone: string;
  paymentMethod: string;
  deliveryAddress: string;
}

// 定义属性
interface Props {
  distributorId: string;
}

const props = defineProps<Props>();

// 事件
const emit = defineEmits<{
  (e: 'view-detail', order: Order): void;
}>();

// 状态
const loading = ref(true);
const orders = ref<Order[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const orderDetailVisible = ref(false);
const selectedOrder = ref<Order | null>(null);

// 筛选器状态
const filters = ref({
  startDate: format(subDays(new Date(), 30), 'yyyy-MM-dd'),
  endDate: format(new Date(), 'yyyy-MM-dd'),
  status: ''
});

// 获取订单数据
const fetchOrders = async () => {
  loading.value = true;
  try {
    // 在实际项目中，这里应该调用API获取数据
    const data = await generateDistributorOrdersData(props.distributorId, 50);
    orders.value = data;
  } catch (error) {
    console.error('获取订单数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 计算属性：筛选后的订单
const filteredOrders = computed(() => {
  let result = [...orders.value];
  
  // 筛选日期范围
  if (filters.value.startDate && filters.value.endDate) {
    result = result.filter(order => {
      const orderDate = order.orderTime.split(' ')[0]; // 提取日期部分
      return orderDate >= filters.value.startDate && orderDate <= filters.value.endDate;
    });
  }
  
  // 筛选状态
  if (filters.value.status) {
    result = result.filter(order => order.status === filters.value.status);
  }
  
  return result;
});

// 计算属性：是否已应用筛选
const isFiltered = computed(() => {
  return filters.value.status !== '' || 
    filters.value.startDate !== format(subDays(new Date(), 30), 'yyyy-MM-dd') ||
    filters.value.endDate !== format(new Date(), 'yyyy-MM-dd');
});

// 计算属性：分页后的订单
const paginatedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredOrders.value.slice(start, end);
});

// 计算属性：总页数
const totalPages = computed(() => {
  return Math.max(1, Math.ceil(filteredOrders.value.length / pageSize.value));
});

// 计算属性：显示的页码
const displayedPages = computed(() => {
  const pages = [];
  const maxVisiblePages = 5;
  
  // 确保总页数不超过最大可见页数
  if (totalPages.value <= maxVisiblePages) {
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i);
    }
    return pages;
  }
  
  // 显示中间页码
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2));
  let endPage = startPage + maxVisiblePages - 1;
  
  // 调整起始页码
  if (endPage > totalPages.value) {
    endPage = totalPages.value;
    startPage = Math.max(1, endPage - maxVisiblePages + 1);
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i);
  }
  
  return pages;
});

// 方法：处理筛选
const handleFilter = () => {
  currentPage.value = 1; // 重置到第一页
};

// 方法：重置筛选条件
const resetFilters = () => {
  filters.value = {
    startDate: format(subDays(new Date(), 30), 'yyyy-MM-dd'),
    endDate: format(new Date(), 'yyyy-MM-dd'),
    status: ''
  };
  handleFilter();
};

// 方法：获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'pending': return '待处理';
    case 'processing': return '处理中';
    case 'completed': return '已完成';
    case 'cancelled': return '已取消';
    default: return '未知状态';
  }
};

// 方法：查看订单详情
const viewOrderDetail = (order: Order) => {
  emit('view-detail', order);
};

// 监听筛选器变化
watch([() => filters.value.status, currentPage], () => {
  // 在实际项目中，可能需要根据筛选条件重新请求数据
});

// 监听分销商ID变化
watch(() => props.distributorId, () => {
  fetchOrders();
  resetFilters();
});

// 生命周期钩子
onMounted(() => {
  fetchOrders();
});
</script>

<style lang="scss" scoped>
.orders-list {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  padding: 0;
  margin-bottom: 24px;
  overflow: hidden;
  
  .filter-section {
    padding: 20px;
    border-bottom: 1px solid #e5e7eb;
    
    .filter-row {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: center;
      
      .date-filter, .status-filter {
        display: flex;
        align-items: center;
        
        label {
          margin-right: 8px;
          font-size: 14px;
          color: #4b5563;
          white-space: nowrap;
        }
      }
      
      .date-inputs {
        display: flex;
        align-items: center;
        
        .date-input {
          padding: 8px 12px;
          border: 1px solid #d1d5db;
          border-radius: 6px;
          font-size: 14px;
        }
        
        .date-separator {
          margin: 0 8px;
          color: #6b7280;
        }
      }
      
      .status-select {
        padding: 8px 12px;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        font-size: 14px;
        color: #1f2937;
        background-color: #fff;
        min-width: 120px;
      }
      
      .reset-btn {
        padding: 8px 16px;
        background-color: #f3f4f6;
        color: #4b5563;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 6px;
        transition: all 0.2s;
        
        &:hover {
          background-color: #e5e7eb;
          color: #1f2937;
        }
        
        i {
          font-size: 12px;
        }
      }
    }
  }
  
  .table-container {
    overflow-x: auto;
    min-height: 200px;
    
    .orders-table {
      width: 100%;
      border-collapse: collapse;
      
      th, td {
        padding: 16px 20px;
        text-align: left;
        border-bottom: 1px solid #e5e7eb;
      }
      
      th {
        background-color: #f9fafb;
        color: #4b5563;
        font-weight: 600;
        font-size: 14px;
      }
      
      td {
        color: #1f2937;
        font-size: 14px;
      }
      
      .products-cell {
        .product-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 4px;
          
          &:last-child {
            margin-bottom: 0;
          }
        }
        
        .product-price {
          color: #6b7280;
          font-size: 13px;
        }
        
        .product-count {
          margin-top: 6px;
          font-size: 13px;
          color: #6b7280;
          font-style: italic;
        }
      }
      
      .amount-cell, .commission-cell {
        font-weight: 600;
      }
      
      .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 16px;
        font-size: 12px;
        font-weight: 500;
        
        &.status-pending {
          background-color: rgba(245, 158, 11, 0.1);
          color: #f59e0b;
        }
        
        &.status-processing {
          background-color: rgba(59, 130, 246, 0.1);
          color: #3b82f6;
        }
        
        &.status-completed {
          background-color: rgba(16, 185, 129, 0.1);
          color: #10b981;
        }
        
        &.status-cancelled {
          background-color: rgba(239, 68, 68, 0.1);
          color: #ef4444;
        }
      }
      
      .view-btn {
        padding: 6px 12px;
        background-color: #f3f4f6;
        color: #4b5563;
        border: none;
        border-radius: 6px;
        font-size: 13px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 4px;
        transition: all 0.2s;
        
        &:hover {
          background-color: #e5e7eb;
          color: #1f2937;
        }
        
        i {
          font-size: 12px;
        }
      }
    }
  }
  
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px;
    
    .spinner {
      width: 40px;
      height: 40px;
      border: 3px solid rgba(74, 108, 247, 0.2);
      border-top-color: #4a6cf7;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 16px;
    }
    
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
    
    p {
      color: #6b7280;
      font-size: 16px;
    }
  }
  
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px;
    
    i {
      font-size: 48px;
      color: #9ca3af;
      margin-bottom: 16px;
    }
    
    p {
      color: #6b7280;
      font-size: 16px;
      margin-bottom: 16px;
    }
    
    button {
      margin-top: 8px;
    }
  }
  
  .pagination {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    border-top: 1px solid #e5e7eb;
    
    .page-btn {
      width: 36px;
      height: 36px;
      border: 1px solid #d1d5db;
      border-radius: 6px;
      background-color: #fff;
      color: #4b5563;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover:not(:disabled) {
        border-color: #4a6cf7;
        color: #4a6cf7;
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
    
    .page-numbers {
      display: flex;
      margin: 0 12px;
      
      .page-number {
        width: 36px;
        height: 36px;
        border: 1px solid #d1d5db;
        background-color: #fff;
        color: #4b5563;
        font-size: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        margin: 0 4px;
        transition: all 0.2s;
        
        &:hover:not(.active) {
          border-color: #4a6cf7;
          color: #4a6cf7;
        }
        
        &.active {
          background-color: #4a6cf7;
          color: #fff;
          border-color: #4a6cf7;
        }
        
        &:first-child {
          border-top-left-radius: 6px;
          border-bottom-left-radius: 6px;
        }
        
        &:last-child {
          border-top-right-radius: 6px;
          border-bottom-right-radius: 6px;
        }
      }
    }
    
    .page-info {
      margin-left: 16px;
      font-size: 14px;
      color: #6b7280;
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .orders-list {
    .filter-section {
      .filter-row {
        flex-direction: column;
        align-items: flex-start;
        
        .date-filter, .status-filter {
          width: 100%;
          margin-bottom: 12px;
          flex-direction: column;
          align-items: flex-start;
          
          label {
            margin-bottom: 6px;
          }
        }
        
        .date-inputs {
          width: 100%;
          
          .date-input {
            flex: 1;
          }
        }
        
        .status-select {
          width: 100%;
        }
        
        .reset-btn {
          width: 100%;
          justify-content: center;
        }
      }
    }
    
    .table-container {
      .orders-table {
        th, td {
          padding: 12px 16px;
        }
      }
    }
    
    .pagination {
      flex-wrap: wrap;
      
      .page-info {
        margin-left: 0;
        margin-top: 12px;
        width: 100%;
        text-align: center;
      }
    }
  }
}
</style> 